import { Modal, Form, Input, Button, message } from "antd"
import { AddParamsFnc, ShowEditParamsFnc, EditParamsFnc } from '@/api/params'
import style from './index.module.scss'
import { useEffect, useState } from "react"

const AddEdit = ({isModalOpen, changeEditBox, activeName, type, catID, getTable, cascaderValue, attrID}: any) => {
  const [form] = Form.useForm()
  const [formObj, setFormObj] = useState({}) // 修改时 用做做对比

  // 打开编辑盒子 数据初始化
  const init = async () => {
    if(attrID !== '') {
      const res = await ShowEditParamsFnc(catID, attrID, {attr_sel: activeName})
      if(res.data.meta.status === 200) {
        form.setFieldsValue({attr_name: res.data.data.attr_name})
        setFormObj({attr_name: res.data.data.attr_name})
      } 
    }
  }
  useEffect(() => {init()}, [attrID])

  // 公告提示消息
  const publicMsg = (msg: string) => {
   message.success(msg, 1.5, () => {
    changeEditBox(false)
    getTable(cascaderValue, activeName)
   })
  }

  // 添加（动态参数 或 静态属性） 修改（动态参数 或 静态属性）
  const onFinish = async (value: {attr_name: string}) => {
    if(type === 'add') {
      const res = await AddParamsFnc(catID, {attr_name: value.attr_name, attr_sel: activeName})
      if(res.data.meta.status === 201) publicMsg('添加成功')
    } else {
      if(JSON.stringify(value) === JSON.stringify(formObj)) { // 未修改
        return 
      } else {
        const res = await EditParamsFnc(catID, attrID, {attr_name: value.attr_name, attr_sel: activeName})
        if(res.data.meta.status === 200) publicMsg('修改成功')
      }
    }
  }
  return (
    <Modal title={activeName === 'many' ? (type=== 'add' ? '添加' : '修改' ) + '动态参数' : (type=== 'add' ? '添加' : '修改') + '静态属性'} open={isModalOpen} footer={null} onCancel={() => changeEditBox(false)}>
       <Form form={form} className={style.form} onFinish={onFinish} labelCol={{ span: 4 }}>
          <Form.Item name="attr_name" label={activeName === 'many' ? '动态参数' : '静态属性'} rules={[{ required: true, message: `请输入${activeName === 'many' ? '动态参数' : '静态属性'}` }, {min: 3, max: 100, message: '长度在3-100个字符'}]}>
            <Input/>
          </Form.Item>
            
          <Form.Item style={{marginBottom: 0}}>
            <div className={style.btn}>
              <Button type="default" onClick={() =>changeEditBox(false)}>取消</Button>
              <Button type="primary" htmlType="submit">{type === 'add' ? '添加' : '修改'}</Button>
            </div>
          </Form.Item>
        </Form>
    </Modal>
  )  
}

export default AddEdit